package com.duobab.springbootsecuritydemo.security;

import com.duobab.springbootsecuritydemo.domain.UserInfo;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

public class SsoContextHolder {
    public static UserInfo getUserInfo() throws JsonProcessingException {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        ObjectMapper objectMapper = new ObjectMapper();
        String authenticationJson = objectMapper.writeValueAsString(authentication.getPrincipal());

        ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        UserInfo userInfo = mapper.readValue(authenticationJson, new TypeReference<UserInfo>() {
        });
        return userInfo;
    }
}
